package com.qipay.sp.excutor.qfpay;

import com.qipay.sp.excutor.qfpay.token.QfpayToken;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.util.Map;


public class QfGetTokenNativeExcutor  {

    private final static String API_URL="http://api.huobapay.com/api/auth/access-token?appid=%s&secretid=%s";

    public static QfpayToken getToken(String appid, String secretid){

        String url = String.format(API_URL, appid, secretid);
        HttpGet hg = new HttpGet(url);
        HttpClient client = new DefaultHttpClient();

        QfpayToken qfpayToken = null;
        try{
            HttpResponse httpResponse = client.execute(hg);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(httpResponse.getEntity(), "utf8");
                Map<String, Object> responseMap = com.qipay.utils.XmlUtils.toMap(result);

                if(responseMap != null){
                    Object token = responseMap.get("token");
                    Object token_expir_second = responseMap.get("token_expir_second");
                    if(token != null){
                        qfpayToken = new QfpayToken();
                        qfpayToken.setToken(token.toString());
                        if(token_expir_second != null){
                            qfpayToken.setExpirSecond(Long.valueOf(token_expir_second.toString()));
                        }
                        qfpayToken.setTimeStamp(System.currentTimeMillis());
                    }else{
                        // TODO LOg
                    }
                }
            }
        }catch (Exception e){
            //TODO log
        }
        return qfpayToken;
    }

}
